<template>
	<view class="warp">
		<view class="page_top" :style="{
            background:  'transparent',
            
        }">
            <top-status></top-status>
            <view class="tabsBack">
                <view @click="goBack()" class="blackbox">
                    <!-- <image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17152491719361330.png"
                                    mode="widthFix"></image> -->
                    <uni-icons :color="'black' " type="left" size="30"></uni-icons>
                </view>
                <!-- <view class="topTitle hiddenText" v-show="topNav">{{
                    $util.entitiesToUtf16(resData.Name)
                }}</view> -->
            </view>
        </view>
        <view class="contentbox">
            <image class="contentimg" :src="resData.IsVideo == 1?imgJSON:imgJSON[0]" mode="aspectFill"></image>
            <view class="contenttext">给大家分享一下最近的滑雪照，觉得不错就快来帮我点赞吧～</view>
            <view class="infobox">
                <view class="userinfo">
                    <image class="infohd" :src="user.HeadImgUrl" mode="aspectFill"></image>
                    <view class="infonabox">
                        <view class="usname">{{user_name?user_name:''}}</view>
                        <view class="title1">我在雪遇参与话题挑战，快来帮我点赞吧！</view>
                    </view>
                </view>
                <view class="qrbox">
                    <image class="qrimg" :src="qr"></image>
                    <!-- <view class="qrtext">长按识别参与</view> -->
                </view>
            </view>
        </view>
		<canvas canvas-id="hoCanvas" class="hoCanvas" :style="{ height: lineBgHeight + 'px' }"></canvas>
		<!-- #ifdef MP-WEIXIN -->
		<button v-if="btnshow" @click="saveImageToAlbum">
			<image class="downimg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17298248241761424.png"></image>
			保存到相册
			</button>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<button v-if="btnshow" @click="saveImageapp">保存相册</button>
		<!-- #endif -->
	</view>
</template>

<script>
import topStatus from "@/components/topStatus/topStatus.vue";
	export default {
        components: {
            topStatus,
        },
		data() {
			return {
                imgJSON:[],
                userratio:'',
                resData:{},
                sum:0,
                Dynamic:'',
				user: [],
				btnshow: false,
				show: false,
				img: '../../static/img/test.png',
				qr: '',
				postUrl: '',
				canvasW: '',
				canvasH: '',
				_rpx: '',
				ratio: '',
				windowWidth: '',
				windowHeight: '',
				cW: '',
				cH:'',
				
				img_w:'',
				img_h:'',
				userwidth:'',
                userheight:'',
				user_name:'',
				img3:'',
				lineBgHeight:570
			};
		},
		watch: {
			'qr': {
				handler(val) {
					console.log(val);
					// this.saveImg();
				},
				immediate: true,
				deep: true
			}
		},
		async onLoad(e) {
            this.Dynamic = e.id
			uni.getSystemInfo({
				success: (res) => {
					this.cW = res.windowWidth;
					this.cH=res.windowHeight;
				}
			})
			// this.img3 = "https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718093981824195.png"
		},
		async onReady() {
            this.getDetail()
			await this.getUserInfo();

			await this.CreateShareQR();

			await this.saveImg();
		},
		computed: {
			getTime2() {
				return (l) => {
					let d = new Date(l);
					let timestamp = d.getTime();
					return this.$util.unixDatetime(timestamp, 'year');
				};
			},
			getTime3() {
				return (l) => {
					let d = new Date(l);
					let timestamp = d.getTime();
					return this.$util.unixDatetime(timestamp, 'hh-mm');
				};
			}
		},
		methods: {
            goBack() {
                const pages = getCurrentPages();
                if (pages.length > 1) {
                    // 如果页面栈长度大于1，则说明有上一页，可以返回
                    uni.navigateBack();
                } else {
                    // 如果没有上一页，则导航到首页
                    uni.reLaunch({
                    url: '/pages/tab/assistant'
                    });
                }
                },
			difference(Hit_Num,Score){
					if((Score - Hit_Num) > 0){
						return '+'+(Score - Hit_Num)
					}else if((Hit_Num - Score) == 0){
						return 0
					}else if((Score - Hit_Num) < 0){
						return '-'+(Hit_Num - Score)
					}
			},
            async getDetail() {
				let res = await this.$api.post('Community/Detail', {
					ID: this.Dynamic
				});
                if(res.code == 0){
                    this.resData = res.data;
					if(res.data.IsVideo == 1){
						this.imgJSON = res.data.HeadImgUrl
					}else{
						this.imgJSON =JSON.parse(res.data.Images) 
					}
                    
                }
				
			},

			async getUserInfo() {
				let u = uni.getStorageSync('user');
				console.log(u.UserID);
				let res = await this.$api.post('User/GetUserInfo', {
					ID: u.UserID
				});

				this.user = res.data;
				
				this.img = this.user.UserImgs;
				this.user_name=this.user.Name;
				
				let that=this;
				// uni.getImageInfo({
				// 	src: 'https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718355071624415.png',
				// 	success: function(res) {
				// 	},
				// 	fail: (res) => {
						
				// 	}
				// });
			},

			async CreateShareQR() {
				let res = await this.$api.post('Action/CreateShareQR', {
					Page: 'pages/dynamic/detail',
                    EventID:this.Dynamic
				})
				console.log(res);
				this.qr = res.data;
				
			},

			saveImg() {
				var that = this;
				let promise1 = new Promise(function(resolve, reject) {
					console.log('promise1', that.img);
					uni.getImageInfo({
						src: that.resData.IsVideo == 1?that.imgJSON:that.imgJSON[0],
						success: function(res) {
							console.log('promise1--', res);
                            that.userwidth = res.width
                            that.userheight = res.height
                            that.ratio = res.width/res.height
                            console.log(that.userwidth,that.userheight,that.ratio ,'that.ratio');
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise1错误');
							console.log(res);
						}
					});
				});
				let promise2 = new Promise(function(resolve, reject) {
					console.log('------');
					console.log('promise2', that.qr);
					uni.getImageInfo({
						src: that.qr,
						success: function(res) {
							console.log('promise2--', res);
							that.show = true
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise2错误');
							console.log(res);
						}
					})
				});
				
				let promise3 = new Promise(function(resolve, reject) {
					
					uni.getImageInfo({
						src: that.img,
						success: function(res) {
							console.log('promise3--', res);
                            that.img_w=res.width;
						    that.img_h=res.height;
                            that.userratio =  res.width / res.height
							that.show = true
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise3错误');
							console.log(res);
						}
					})
				});
                let promise4 = new Promise(function(resolve, reject) {
					console.log('------');
					uni.getImageInfo({
						src: 'https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1727595577840880.png',
						success: function(res) {
							console.log('promise4--', res);
							that.show = true
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise4错误');
							console.log(res);
						}
					})
				});
				// wx.getSystemInfo({
				// 	success: (res) => {
				// 		//that._rpx = res.windowWidth / 375;
				// 		that.ratio = res.windowWidth / res.windowHeight
				// 		// this.windowWidth = res.windowWidth
				// 		// this.windowHeight = res.windowHeight
				// 	},
				// })
                setTimeout(()=>{
                    const query = uni.createSelectorQuery();
				    query.select('.hoCanvas').fields({
							node: true, //指定要获取的属性，这里设置为size: true表示要获取尺寸信息。
							size: true, //在回调函数(res) => {...}中处理查询结果。回调函数会接收一个res参数，其中包含了查询的结果信息。
						},
						(res) => {
							// const dpr = wx.getWindowInfo().pixelRatio
							
							// 在回调函数中，通过res.width和res.height获取到查询元素的宽度和高度。
							console.log(res,'resres');
							
							let hdheight = (331/that.userratio)+10
							const imgRatio = Number(that.ratio) 
							console.log(imgRatio);
							let bNum = 1
							that.canvasW = 375 *bNum;
							that.canvasH = 617 * bNum;
							// that.lineBgHeight = hdheight+150
							console.log(this.canvasW,this.canvasH);
							// 绘制图片：图片居中显示在 canvas 中

							Promise.all([promise4,promise1,promise3,promise2]).then((res) => {
								that.show = true
								uni.showLoading({
									title: '海报图片生成中...',
									icon: 'loading',
									duration: 1000,
								});
								console.log(res,'resres2');
                                
								/* 图片获取成功才执行后续代码 */
								var canvas = uni.createCanvasContext('hoCanvas');
								canvas.canvasWidth = that.canvasW; // 背景图片的实际宽度
                				canvas.canvasHeight = that.lineBgHeight ;
                                console.log(res[0].path,'res[1].path');
								// 绘制背景图
								canvas.globalAlpha = 0.3;
								canvas.drawImage(res[1].path, 0, 0, that.canvasW,that.canvasH);
								canvas.globalAlpha = 1;
								canvas.drawImage(res[0].path, 30, 12, 315,544);
								// 设置圆角的大小
								const cornerRadius = 20;
								
								// 设置圆角矩形的位置和大小
								const x = 42;
								const y = 22;
								const width = 291;
								const height = 380;
								
								// 创建圆角矩形
								canvas.save();
								canvas.moveTo(x + cornerRadius, y); // 左上角
								canvas.lineTo(x + width - cornerRadius, y);
								canvas.quadraticCurveTo(x + width, y, x + width, y + cornerRadius); // 右上角
								canvas.lineTo(x + width, y + height - cornerRadius);
								canvas.quadraticCurveTo(x + width, y + height, x + width - cornerRadius, y + height); // 右下角
								canvas.lineTo(x + cornerRadius, y + height);
								canvas.quadraticCurveTo(x, y + height, x, y + height - cornerRadius); // 左下角
								canvas.lineTo(x, y + cornerRadius);
								canvas.quadraticCurveTo(x, y, x + cornerRadius, y);
								canvas.closePath();
								
								// 剪切出圆角区域
								canvas.clip();
								// let imgwidth = that.userwidth == that.userheight?(that.userwidth/2) - (291/2):that.userwidth > that.userheight?(that.userwidth/2) - (291/2):0
								// let imgheight = that.userwidth < that.userheight?(that.userheight/2) - (380/2):0
								
								// console.log(imgwidth,imgheight,'999999');
							
								// 绘制图片
								canvas.drawImage(res[1].path, 42, 22,291,380);
								canvas.restore();

                                canvas.font = "14px Arial";
                                canvas.setFillStyle("#666666");
                                canvas.fillText("给大家分享一下最近的滑雪照，觉得不错就快", 42, 430);
                                canvas.font = "14px Arial";
                                canvas.setFillStyle("#666666");
                                canvas.fillText("来帮我点赞吧～", 42, 452);
                                canvas.save();
                                canvas.arc(62, 484, 20, 0, 2 * Math.PI);
                                canvas.clip();
                                canvas.drawImage(res[2].path, 42,464, 40, 40);
                                canvas.restore();
								
								canvas.font = "bold 16px Arial";
                                canvas.setFillStyle("#0D0D0D");
                                canvas.setStrokeStyle("#0D0D0D");
                                let userName = that.$util.entitiesToUtf16(that.user_name);
                                canvas.fillText(userName, 94, 480);
                                canvas.font = "10px Arial";
                                canvas.setFillStyle("#666666");
                                canvas.fillText("我在雪遇参与话题挑战，快来", 94, 497);
                                canvas.font = "10px Arial";
                                canvas.setFillStyle("#666666");
                                canvas.fillText("帮我点赞吧！", 94, 516);
                                canvas.drawImage(res[3].path, 276,463, 60, 60);
                                canvas.font = "10px Arial";
                                canvas.setFillStyle("#999999");
                                // canvas.fillText("长按识别参与", 270, 535);
                                canvas.scale(2,2);
								canvas.draw();

								setTimeout(function() {									
									uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: that.canvasW,
										height:that.lineBgHeight,
										destWidth: that.canvasW*2,
										destHeight: that.lineBgHeight*2,
										// destWidth: 375 ,
										// destHeight: 660,
										canvasId: 'hoCanvas',
										success: function(res) {
											console.log(res.tempFilePath,'111');
											
											that.postUrl = res.tempFilePath;
											// that.saveImageToAlbum();
											that.btnshow = true
											uni.hideLoading();
										},
										fail: function(res) {
											console.log(res,'err');
											
										},
									},this);

								}, 3000);
							}).catch(err => {
								console.dir('出错了', err);
								console.log(err);
								uni.showModal({
									title: '异常错误',
									content: '图片生成失败!!!\n[QRError:Damaged QR code]',
									showCancel: false,
									success: (res) => {
										if (res.confirm) uni.navigateBack()
									}
								})
							})

						}
					)
					.exec();
                },1000)
				
			},
			drawCircleImage(ctx, list,height) {
				for (let i = 0; i < list.length; i++) {
						if(i > 8){
							ctx.font='500 12px Arial';
							ctx.setFillStyle('#666666');
							ctx.setStrokeStyle('#666666');
							ctx.textAlign = 'center'
							ctx.fillText(list[i].HoleNO, 20+((i-9)*25),height+117);
							if(list[i].Hit_Num > list[i].Score){
								ctx.beginPath();
								ctx.fillStyle = '#706EEE'
								ctx.arc(20+((i-9)*25), height+130, 12, 0, 2 * Math.PI);
								ctx.fill();
							}
							ctx.font='700 12px Arial';
							ctx.setFillStyle('#333333');
							ctx.setStrokeStyle('#333333');
							if(list[i].Hit_Num > list[i].Score){
								ctx.setFillStyle('#fff');
								ctx.setStrokeStyle('#fff');
							}
							ctx.fillText(this.difference(list[i].Hit_Num,list[i].Score), 20+((i-9)*25),height+134);
						}else{
							ctx.textAlign = 'center'
							ctx.font='500 12px Arial';
							ctx.setFillStyle('#666666');
							ctx.setStrokeStyle('#666666');
							ctx.fillText(list[i].HoleNO, 20+((i)*25),height+75);
							if(list[i].Hit_Num > list[i].Score){
								ctx.beginPath();
								ctx.fillStyle = '#706EEE'
								ctx.arc(20+((i)*25), height+91, 12, 0, 2 * Math.PI);
								ctx.fill();
							}
							ctx.font='700 12px Arial';
							ctx.setFillStyle('#333333');
							ctx.setStrokeStyle('#333333');
							if(list[i].Hit_Num > list[i].Score){
								ctx.setFillStyle('#fff');
								ctx.setStrokeStyle('#fff');
							}
							ctx.fillText(this.difference(list[i].Hit_Num,list[i].Score), 20+((i)*25),height+95);
						}
						
				}
			},
			saveImageToAlbum: function() {
				var that = this;
				//将图片保存到相册
				uni.saveImageToPhotosAlbum({
					filePath: that.postUrl,
					success(res) {
						uni.showModal({
							title: '保存成功',
							content: '图片成功保存到相册了，快去分享朋友圈吧',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#818FFB',
							success: function(res) {
								if (res.confirm) {}
								// that.hideShareImg()
							},
						});
					},
				});
			},
			saveImageapp(){
				uni.getImageInfo({
					src: this.postUrl,
					success: function(res) {
						let path = res.path;
						uni.saveImageToPhotosAlbum({
							filePath: path,
							success(res) {
							uni.showToast({
								title: '保存成功',
								icon: "none"
							})
							},
							ail(res) {
								uni.showToast({
									title: '保存失败',
									icon: "none"
								})
							}
						})
					}
				})
				console.log('1111111');
				console.log(this.postUrl,'2222');
			},
		},
	};
</script>

<style lang="scss">
page{
	background-color: rgba(0,0,0,0.3);
}
	.warp {
		width: 100%;
		box-sizing: border-box;
		padding-bottom: 160rpx;
	}
    .contentbox{
        width: 630rpx;
        height: 1088rpx;
        background: #FFFFFF;
        border-radius: 32rpx;
        margin: 240rpx auto;
        margin-bottom: 0;
		padding-bottom: 10rpx;
        .contentimg{
            width: 582rpx;
            height: 760rpx;
            border-radius: 32rpx;
            margin: 24rpx;
        }
        .contenttext{
            font-size: 28rpx;
            width: 580rpx;
            color: #666666;
            margin: 0rpx 24rpx;
        }
    }
    .infobox{
            display: flex;
            align-items: center;
            margin: 0 24rpx;
            .userinfo{
                display: flex;
                margin-right: 30rpx;
                .infohd{
                    width: 80rpx;
                    height: 80rpx;
                    border-radius: 50%;
                    margin-right: 24rpx;
                }
                .infonabox{
                    width: 334rpx;
                    .usname{
                        font-size: 32rpx;
                        color: #0D0D0D;
                        font-weight: bold;
                    }
                    .title1{
                        font-size: 24rpx;
                        color: #979797;
                    }   
                }
            }
            .qrbox{
                .qrimg{
                    width: 108rpx;
                    height: 108rpx;
                    border-radius: 50%;
                }
                .qrtext{
                    font-size: 20rpx;
                    color: #999999;
                }
            }
        }
	.hoCanvas {
		width: 375px;
		height: 617px;
		margin: 50rpx auto;
		margin-bottom: 0;
		box-sizing: border-box;
		position:fixed;
		left: -200%;
		top: -200%;
		opacity: 0;
		z-index: -99;
	}

	.height70 {
		height: 70vh;
	}
	
	.height100 {
		height: 100vh;
	}

	.height64 {
		height: 62vh;
	}

	button {
		position: fixed;
		left: 50%;
		bottom: 40rpx;
		transform: translate(-50%, -50%);
		background-color: #0D0D0D;
		color: #fff;
		border-radius: 42rpx;
		width: 90vw;
		margin: 0 auto;
        z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
		.downimg{
			width: 40rpx;
			height: 40rpx;
		}
	}
.page_top {
  position: fixed;
  top: 0;
  left: 0;
  width: 750rpx;
  box-sizing: border-box;
  transition: 0.3s all;

  // background: #29282c;
  // z-index: 999999;
  .tabsBack {
    height: 44px;
    padding-left: 32rpx;
    display: flex;
    align-items: center;
    z-index: 999;

    .topTitle {
      padding-left: 20rpx;
      font-weight: bold;
      font-size: 36rpx;
      color: #333333;
      width: 300rpx;
    }

    .blackbox {
      width: 52rpx;
      height: 52rpx;
      display: flex;
      align-items: center;
    }

    image {
      width: 24rpx;
      height: 36rpx;
      display: block;
    }
  }

  .tabs {
    position: relative;
    display: flex;
    // align-items: center;
    height: 900rpx;

    .changeImg {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: absolute;
      bottom: 60rpx;
      right: 10rpx;
      font-size: 20rpx;
    }

    >image {
      width: 100%;
      height: 100%;
    }

    .name {
      font-size: 36rpx;
      color: #fff;
      padding-left: 20rpx;
      width: 200rpx;
    }

    button {
      width: 50rpx;
      height: 50rpx;
      position: absolute;
      right: 40rpx;
      top: 40rpx;
      text-align: center;
      line-height: 50rpx;

      image {
        width: 50rpx;
        height: 50rpx;
      }
    }

    .onlin {
      position: absolute;
      left: 40rpx;
      top: 6%;
      width: 208rpx;
      height: 44rpx;
      background: #ffffff;
      border-radius: 22px;
      line-height: 44rpx;
      color: #1db468;
      font-size: 24rpx;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;

      &::before {
        content: "";
        display: inline-block;
        background: #1db468;
        width: 12rpx;
        height: 12rpx;
        border-radius: 8rpx;
        margin-right: 8rpx;
      }
    }
  }
}
</style>